package com.sias.realestate.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sias.realestate.web.model.Owner;
import com.sias.realestate.web.model.Tenement;
import com.sias.realestate.web.service.OwnerService;
import com.sias.realestate.web.service.TenementService;
import com.sias.realestate.web.util.FinalVarUtil;
import com.sias.realstate.web.pagemodel.PageModel;

@Controller
@RequestMapping(value = "/tenement")
public class TenementController {

	@Resource
	private TenementService tenementService;
	@Resource
	private OwnerService ownerService;

	@RequestMapping(value = "/getAllTenement", method = RequestMethod.GET)
	public ModelAndView getAllTenement(HttpServletRequest request)
			throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		ModelAndView mv = new ModelAndView();
		PageModel pageModel = new PageModel();
		List<Tenement> list = tenementService.selectList();
		String th_list = FinalVarUtil.tenementTh;
		pageModel.setTh_list(th_list);
		mv.addObject("pageModel", pageModel);
		mv.addObject("list", list);
		mv.setViewName("tenement/tenementList");
		return mv;
	}
	/**
	 * 
	 * @param model
	 * @param request
	 * @return 
	 * 方法说明：删除房屋信息
	 */
	@RequestMapping(value = "/deleteTenement", method = RequestMethod.GET)
	public ModelAndView deleteTenement(HttpServletRequest request,Integer tid) {
		ModelAndView mv = new ModelAndView("redirect:getAllTenement");
	    tenementService.delete(tid);
		return mv;
	}

	/**
	 * 
	 * @param model
	 * @param request
	 * @return 方法说明：离住 创建日期：2016年12月15日下午4:58:07
	 */
	@RequestMapping(value = "/leaveTenement", method = RequestMethod.GET)
	public ModelAndView leaveTenement(HttpServletRequest request, Integer tid) {
		Tenement tenement = tenementService.selectById(tid);
		String idcard = tenement.getoIdcard();
		// 通过idcard找到业主将状态改为0离住
		Owner owner = ownerService.findByIdcard(idcard);
		owner.setoStatus("0");
		owner.setoLeave(new Date());
		tenement.setoIdcard("");
		ownerService.update(owner);
		tenementService.update(tenement);
		ModelAndView mv = new ModelAndView();
		PageModel pageModel = new PageModel();
		List<Tenement> list = tenementService.selectList();
		String th_list = FinalVarUtil.tenementTh;
		pageModel.setTh_list(th_list);
		mv.addObject("pageModel", pageModel);
		mv.addObject("list", list);
		mv.setViewName("tenement/tenementList");
		return mv;
	}

	/**
	 * 
	 * @param model
	 * @param request
	 * @return 方法说明：上传房屋信息 
	 * @throws IOException
	 */
	@RequestMapping(value = "/addTenement", method = RequestMethod.POST)
	public ModelAndView addTenement(HttpServletRequest request, MultipartFile ufile) throws IOException {
		ModelAndView mv = new ModelAndView();
		PageModel pageModel = new PageModel();
		if (ufile != null) {
			String targetFileName = ufile.getOriginalFilename();
			String targetDirectory = request.getSession().getServletContext().getRealPath("//upload");
			File target = new File(targetDirectory, targetFileName);	// 生成上传对象;
			if (target.exists()) {// 如果文件已经存在，则删除原有文件
				target.delete();
			}
			try {// 复制文件
				FileUtils.copyInputStreamToFile(ufile.getInputStream(), target);
			} catch (Exception e) {
				e.printStackTrace();
			}
			readXls(target.toString());
			List<Tenement> list = tenementService.selectList();
			String th_list = FinalVarUtil.tenementTh;
			pageModel.setTh_list(th_list);
			mv.addObject("pageModel", pageModel);
			mv.addObject("list", list);
			mv.setViewName("tenement/tenementList");
		}
		return mv;
	}

	public List<Tenement> readXls(String path) throws IOException {
		InputStream is = new FileInputStream(path);
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
		Tenement tenement = null;
		List<Tenement> list = new ArrayList<Tenement>();
		HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);

		// Read the Row
		List<Tenement> tenementList = new ArrayList<Tenement>();
		for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
			HSSFRow hssfRow = hssfSheet.getRow(rowNum);
			if (hssfRow != null) {
				tenement = new Tenement();
				HSSFCell dong = hssfRow.getCell(0);
				HSSFCell unit = hssfRow.getCell(1);
				HSSFCell num = hssfRow.getCell(2);
				HSSFCell area = hssfRow.getCell(3);
				tenement.settDong(getValue(dong));
				tenement.settUnit(getValue(unit));
				tenement.settNum(getValue(num));
				tenement.setoIdcard("");
				tenement.settArea(getValue(area));
				tenementList.add(tenement);
			}
		}
		tenementService.addTenement(tenementList);
		return list;
	}

	@SuppressWarnings("static-access")
	private String getValue(HSSFCell hssfCell) throws NullPointerException {
		String cellValue = "";
		switch (hssfCell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:// 字符串类型
			cellValue = hssfCell.getStringCellValue();
			if (cellValue.trim().equals("") || cellValue.trim().length() <= 0)
				cellValue = " ";
			break;
		case HSSFCell.CELL_TYPE_NUMERIC: // 数值类型
			cellValue = String.valueOf((int) hssfCell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_FORMULA: // 公式
			hssfCell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
			cellValue = String.valueOf((int) hssfCell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			cellValue = " ";
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			break;
		case HSSFCell.CELL_TYPE_ERROR:
			break;
		default:
			break;
		}
		return cellValue;
	}

}
